package com.nari.ncps.screen.service.impl.coal;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.coal.CoalSafetyenvRiskDeal;
import com.nari.ncps.screen.mapper.coal.CoalSafetyenvRiskDealMapper;
import com.nari.ncps.screen.service.coal.CoalSafetyenvRiskDealService;
import com.nari.ncps.screen.vo.coal.CoalWasteDisposalVO;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 安全环保危险废弃物处置表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class CoalSafetyenvRiskDealServiceImpl extends ServiceImpl<CoalSafetyenvRiskDealMapper, CoalSafetyenvRiskDeal> implements CoalSafetyenvRiskDealService {

    @Override
    public List<CoalWasteDisposalVO> getWasteDisposal(Integer year) {
        // 获取当前日期，用于确定最近6个月的范围
        LocalDate currentDate = LocalDate.now();
//        LocalDate sixMonthsAgo = currentDate.minusMonths(5); // 包含当前月在内的6个月
        //TODO 当前数据不全部可取六个月的数据，要取10个月的数据
        LocalDate sixMonthsAgo = currentDate.minusMonths(9); // 包含当前月在内的6个月


        // 查询最近6个月的数据
        QueryWrapper<CoalSafetyenvRiskDeal> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("year", sixMonthsAgo.getYear())
                    .le("year", currentDate.getYear())
                    .orderByDesc("year")
                    .orderByDesc("month")
                    .last("LIMIT 6");
        
        // 如果指定了具体月份范围，可以进一步过滤
        if (year != null) {
            queryWrapper.eq("year", year);
        } else {
            // 更精确的月份过滤
            queryWrapper.and(wrapper -> {
                wrapper.gt("year", sixMonthsAgo.getYear())
                      .or()
                      .eq("year", sixMonthsAgo.getYear()).ge("month", sixMonthsAgo.getMonthValue());
            });
            queryWrapper.and(wrapper -> {
                wrapper.lt("year", currentDate.getYear())
                      .or()
                      .eq("year", currentDate.getYear()).le("month", currentDate.getMonthValue());
            });
        }
        
        List<CoalSafetyenvRiskDeal> riskDealList = this.list(queryWrapper);
        
        // 转换为VO对象
        return riskDealList.stream().map(entity -> {
            CoalWasteDisposalVO vo = new CoalWasteDisposalVO();
            vo.setYear(entity.getYear());
            vo.setMonth(entity.getMonth());
            vo.setHazardousWasteGenerated(entity.getHazardousWasteGenerated());
            vo.setHazardousWasteTreated(entity.getHazardousWasteTreated());
            vo.setTreatmentRate(entity.getTreatmentRate());
            return vo;
        }).collect(Collectors.toList());
    }

}
